Skip to content
标签
工具
消息
字数
1013 字
阅读时间
6 分钟

邮件发送工具类

java

/**
 * 邮件发送工具类
 * @author chenli
 *
 */
@Service
public class MailUtils implements IPropertyChangeSubscriber{
	private static Logger logger = LoggerFactory.getLogger(MailUtils.class);
	
	@Override
	public String getName() {
		return "邮箱发送工具类";
	}
	
	@Override
	public void notice(List<IProperty> propertys) {
//		init();
	}
	
	/**
	 * 连接信息初始化方法
	 * @author chenli
	 */
	public Session getSession(){
		Properties props = new Properties();
		String server = PropertyEnum.MAIL_HOST.getValue();
		String port = PropertyEnum.MAIL_PORT.getValue();
		String user = PropertyEnum.MAIL_USER.getValue();
		String password = PropertyEnum.MAIL_PASSWORD.getValue();
		if(StringUtils.isBlank(server) || StringUtils.isBlank(port) 
				|| StringUtils.isBlank(user) || StringUtils.isBlank(password)){
			logger.error("请前往【系统配置】设置邮件发送,【host:{},port:{},user:{},passowrd:{}】", server,port,user,password);
			return null;
		}
		if(PropertyEnum.MAIL_SSL.isTrue()){
			//开启SSL加密
			MailSSLSocketFactory mssf = null;
			try {
			    mssf = new MailSSLSocketFactory();
			    mssf.setTrustAllHosts(true);
				props.put("mail.smtp.ssl.enable", "true");
				props.put("mail.smtp.ssl.socketFactory", mssf);
				props.put("mail.smtp.socketFactory.fallback", "false"); //只处理SSL的连接, 对于非SSL的连接不做处理
				props.put("mail.smtp.socketFactory.port", port);
			} catch (GeneralSecurityException e) {
			    logger.error("邮件发送开启SSL加密错误,邮箱服务器:{},SSL端口号:{}", server, port, e);
			}
		}else{
			props.put("mail.smtp.port", port);
		}
		//连接超时时间,单位毫秒
		props.put("mail.smtp.connectiontimeout", 30000);
		//发送超时时间,单位毫秒
		props.put("mail.smtp.timeout", 30000);
		
		props.put("mail.smtp.host", server);
		props.put("mail.smtp.auth", "true");
		return Session.getDefaultInstance(props, null);
	}
	
	public Transport getTransport(Session session){
		String server = PropertyEnum.MAIL_HOST.getValue();
		String port = PropertyEnum.MAIL_PORT.getValue();
		String user = PropertyEnum.MAIL_USER.getValue();
		String password = PropertyEnum.MAIL_PASSWORD.getValue();
		Transport transport = null;
		try {
			transport = session.getTransport("smtp");
			transport.connect(server, Integer.parseInt(port), user, password);
		} catch (Exception e) {
			logger.error("发送邮件,邮件服务器【host:{},port:{},user:{},passowrd:{}】连接失败!", server, port, user, password, e);
		}
		return transport;
	}
	
	/**
	 * 邮件发送
	 * @param email 接收者邮箱
	 * @param subject 标题
	 * @param body 内容支持html格式
	 * @return
	 * @author hero706309@163.com
	 */
	public boolean sendEmail(String email, String subject, String body){
		if(StringUtils.isBlank(email)){
			logger.error("邮箱地址为空,发送失败");
			return false;
		}
		boolean result =true;
		String server = PropertyEnum.MAIL_HOST.getValue();
		String port = PropertyEnum.MAIL_PORT.getValue();
		String user = PropertyEnum.MAIL_USER.getValue();
		String password = PropertyEnum.MAIL_PASSWORD.getValue();
		String fromname = PropertyEnum.MAIL_USERNAME.getValue();
		try {
			Session session = getSession();
			if(session == null){
				return false;
			}
			MimeMessage msg = new MimeMessage(session);
			msg.setSentDate(new Date());
			InternetAddress fromAddress = new InternetAddress(user, fromname, IConstant.ENCODING_UTF8);
			msg.setFrom(fromAddress);
			InternetAddress[] toAddress = new InternetAddress[1];
			toAddress[0] = new InternetAddress(email);
			msg.setRecipients(Message.RecipientType.TO, toAddress);
			msg.setSubject(subject, IConstant.ENCODING_UTF8);
			msg.setContent(body, "text/html; charset=utf-8");
			msg.saveChanges();
			Transport transport = getTransport(session);
			try {
				if(transport == null){
					return false;
				}
				transport.sendMessage(msg, msg.getAllRecipients());
				transport.close();
			} catch (Exception e) {
				logger.error("发送邮件【tomail:{},subject:{},content:{}】失败,邮件服务器【host:{},port:{},user:{},passowrd:{}】", email, subject, body, server,port,user,password, e);
				result = false;
			}
		} catch (Exception e) {
			logger.error("发送邮件【tomail:{},subject:{},content:{}】失败,邮件服务器【host:{},port:{},user:{},passowrd:{}】", email, subject, body, server,port,user,password, e);
			result = false;
		}
		return result;
	}

	/**
	 * 根据属性获取imap 协议的session。
	 * @param server 服务器
	 * @param port 端口
	 * @param isSSL 是否启用ssl
	 * @return
	 * @author chenli
	 * @data 2017-7-3
	 */
	public Session initImapSession(String server,Integer port,boolean isSSL){
		// 获取默认会话
		Properties prop = System.getProperties();
		prop.put("mail.imap.host", server);
		prop.put("mail.imap.port", port);
		//开启debug模式
		//mailsession.setDebug(true); 
		//开启SSL加密
		if(isSSL){
			try {
				MailSSLSocketFactory mssf = new MailSSLSocketFactory();
				mssf.setTrustAllHosts(true);
				prop.put("mail.imap.ssl.enable", "true");
				prop.put("mail.imap.ssl.socketFactory", mssf);
				prop.put("mail.imap.socketFactory.fallback", "false"); //只处理SSL的连接, 对于非SSL的连接不做处理
				prop.put("mail.imap.socketFactory.port", port);
			} catch (Exception e) {
				logger.error("初始化imap session异常service={},port={},isSSL={}",server,port,isSSL, e);
			}
		}else{
			prop.put("mail.imap.host", server);
		}
		Session session = Session.getInstance(prop, null);
		return session;
	}
	
	/**
	 * 获取用户邮箱未读数。 返回-1表示账号密码认证失败
	 * @param server 服务器
	 * @param port 端口
	 * @param isSSL 是否启用ssl
	 * @param username 用户名
	 * @param password 密码
	 * @return
	 * @author chenli
	 * @data 2017-7-3
	 */
	public int getUnreadNum(String server,Integer port,boolean isSSL, String username, String password){
		Session session = initImapSession(server, port, isSSL);
		return getUnreadNum(session, username, password);
	}
	/**
	 * 获取用户邮箱未读数。 返回-1表示账号密码认证失败
	 * @param session 会话
	 * @param username 用户名
	 * @param password 密码
	 * @return
	 * @author chenli
	 * @data 2017-7-3
	 */
	public int getUnreadNum(Session session, String username, String password){
		int result = 0;
		if(session == null || StringUtils.isBlank(username) || StringUtils.isBlank(password)){
			logger.warn("获取邮件未读数,账号为空!username={}",username);
			return result;
		}
		try {
			Store store = session.getStore("imap"); // 使用imap会话机制,连接服务器
			store.connect(username, password);
			Folder folder =  store.getDefaultFolder().getFolder("INBOX");
			folder.open(Folder.READ_ONLY);
			try {
				result = folder.getUnreadMessageCount();
			} catch (Exception e) {
				logger.error("获取邮件未读数失败!username={}",username,e);
			} finally {
				close(folder,store);
			}
		} catch (NoSuchProviderException e) {
			logger.error("获取邮件未读数失败,不支持imap协议!server={}",session.getProperties().getProperty("mail.imap.host"),e);
		} catch (AuthenticationFailedException e){
			logger.error("获取邮件未读数失败,账号【username={},password={}】验证失败={}",username,password, e.getMessage());
			result = -1;
		} catch (MessagingException e) {
			logger.error("获取邮件未读数失败",e);
		}
		
		return result;
	}
	
	/**
	 * 完成邮箱请求后退出邮箱收件箱以释放资源
	 * @param folder
	 * @param store
	 * @author wangyujie
	 * @data 2017年6月26日
	 */
	public static void close(Folder folder,Store store){
		// 释放资源
		try {
			if (folder != null){
				folder.close(true); // 退出收件箱时,删除做了删除标识的邮件
			}
			if (store != null){
				store.close();
			}
		} catch (Exception e) {
			logger.error("断开邮箱连接失败!",e);
		}
	}
}